package cn.tedu._03vehice.controller;

import cn.tedu._03vehice.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = "04.文件上传模块")
@RequestMapping("/v1/file/")
public class UploadController {

    @PostMapping("upload")
    @ApiOperation("文件上传功能")
    @ApiOperationSupport(order = 10)
    public JsonResult upload(MultipartFile file) throws IOException {
         /*
            1.接收客户端传递的数据[文件];
            2.把文件保存到服务器上[d:/files];
            3.返回响应[文件保存的完整路径];
         */
        //*******终极目标:   d:/files/2025/04/16/全局唯一的文件名.png   ***********
        //1.获取原始的文件名: zhly.png
        String filename = file.getOriginalFilename();
        //2.获取文件名的后缀: .png
        String suffix = filename.substring(filename.lastIndexOf("."));
        //3.生成一个全球唯一的随机字符串,作为新的文件名: 4eceb526-83e2-4459-9f7e-5214f61d4997.png
        filename = UUID.randomUUID() + suffix;
        log.debug("文件名:{}", filename);
        //4.自定义日期格式的路径: /yyyy/MM/dd/  比如: /2025/04/16/
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        log.debug("日期路径:{}", datePath);
        //5.定义静态资源路径
        String staticPath = "c:/files";
        //6.创建目录
        File dirFile = new File(staticPath + datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //7.保存文件到服务器
        //  d:/files/2025/04/16/4eceb526-83e2-4459-9f7e-5214f61d4997.png
        String filePath = staticPath + datePath + filename;
        file.transferTo(new File(filePath));
        //返回响应: {"state":2000, "message":"操作成功", "data":"/2025/04/16/xxx.png"}
        //前端工程师:获取数据data,并拼接完整的URL地址,用于页面中显示图片
        //         http://localhost:8080/2025/04/16/xxx.png
        return JsonResult.ok(datePath + filename);
    }
}
